package MainFunctionsDAOS;
import java.awt.*;
import javax.swing.*;
import java.sql.*;
import module4.MySQLConnection;
import java.util.Vector;


public class Table extends JPanel
{
	
	private Statement stmt;
	private ResultSetMetaData resMet = null;
	private ResultSet rs = null;
	private Vector dataVect = null;
	private Vector headingVect = null;
	private Vector stockVect = null;
	

	public Table() 
	{
		try
		{
			MySQLConnection msc = new MySQLConnection("127.0.0.1", "TurtleData", "", "");
			msc.registerDriver();
			msc.connect();
			stmt = msc.getConnection().createStatement(
			ResultSet.TYPE_SCROLL_SENSITIVE,
			ResultSet.CONCUR_READ_ONLY);
		}
		catch(ClassNotFoundException cnfe)
		{
			cnfe.printStackTrace();
		}
		catch(SQLException sqle)
		{
			sqle.printStackTrace();
		}
		
		
	}
	
	public JTable createStockSearchTable(String searchTerm)
	{
		JTable table = null;
		try
		{
			String query = "SELECT * FROM stockTable WHERE title LIKE '" + searchTerm + "%' ORDER BY title ASC";
			ResultSet rs = stmt.executeQuery(query);
			resMet = rs.getMetaData();
			dataVect = new Vector(createDataVect(rs));
			headingVect = new Vector(createHeadingVect(rs));
			table = new JTable(dataVect, headingVect);
			table.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
			table.setAutoCreateRowSorter(true);
			
			
		}
		catch(SQLException sqle)
		{
			sqle.printStackTrace();
		}
		return table;			
	}
	
	public Vector createDataVect(ResultSet rs) throws SQLException
	{
		Vector vect = new Vector();
		while(rs.next())
		{
			Vector innerVect = new Vector();
			int i = 1;
			//System.out.println("rs.getString(i): " + rs.getString(i));
			//System.out.println("rs.getString(i).length(): " + rs.getString(i).length());
			while(i <= resMet.getColumnCount())
			{
				innerVect.add(rs.getString(i));
				i++;
			}
			vect.add(innerVect);
		}
		return vect;
	}
	
	public Vector createHeadingVect(ResultSet rs) throws SQLException
	{
		
		Vector vect = new Vector(resMet.getColumnCount());
		int i = 1;
		while(i <= resMet.getColumnCount())
		{
			System.out.println(resMet.getColumnName(i));
			i++;
		}
		i=1;
		while(i <= resMet.getColumnCount())
		{
			vect.add(resMet.getColumnName(i));
			i++;
		}
		
		return vect;
	}
	
	public Vector createStockItemVect(Vector dataVect)
	{
		stockItem si = new stockItem(dataVect[0][0]);
	}
}

